package app.sceledroid.activity;

import java.util.ArrayList;

import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import app.sceledroid.R;
import app.sceledroid.services.SceleService;
import app.sceledroid.services.SceleService.SceleBinder;
import app.sceledroid.adapter.CourseAdapter;
import app.sceledroid.entity.Course;
import app.sceledroid.activity.CourseActivity;

public class MainActivity extends Activity {

	public static SceleService sceleService;
	private boolean isBounded;
	private ArrayList<Course> courses;
	private CourseAdapter courseAdapter;

	private ServiceConnection sceleServiceConnection = new ServiceConnection() {

		//@Override
		public void onServiceConnected(ComponentName componentName,
				IBinder iBinder) {
			// TODO Auto-generated method stub
			SceleBinder binder = (SceleBinder) iBinder;
			sceleService = binder.getService();
			isBounded = true;
		}

		//@Override
		public void onServiceDisconnected(ComponentName componentName) {
			// TODO Auto-generated method stub
			isBounded = false;
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		courses = new ArrayList<Course>();
		courseAdapter = new CourseAdapter(this, R.id.list_no_item, courses);
		// courseAdapter.add(new Course("asuhdiuasd", "adhsaiuhdoias"));
		
		Intent service = new Intent(this, SceleService.class);
		startService(service);

		final Button fetchButton = (Button) findViewById(R.id.fetch_course);
		ListView courseListView = (ListView) findViewById(R.id.courseList);
		courseListView.setOnItemClickListener(new OnItemClickListener() {

			//@Override
			public void onItemClick(AdapterView adapterView, View view,
					int index, long position) {
				// TODO Auto-generated method stub
				if (sceleService != null) {
					Intent intent = new Intent(MainActivity.this,
							CourseActivity.class);

					Course c = courseAdapter.getItem(index);
					Log.v("Selected", "Selected Course : " + c.getName());
					
					if (sceleService.getDeadline(c.getName()) == null)
					{
						sceleService.fetchCourseItem(MainActivity.this, c);
						
					}
					else if (sceleService.getDeadline(c.getName()).size() == 0) {
						Toast.makeText(MainActivity.this,
								"Deadline not fetched", Toast.LENGTH_LONG)
								.show();
						sceleService.fetchCourseItem(MainActivity.this, c);
						
					}
					intent.putExtra("URL", c.getUrl());
					intent.putExtra("CourseName", c.getName());
					startActivity(intent);
				}
				else
				{
					bindToService();
					Toast.makeText(MainActivity.this, "SceleService IS NULL", Toast.LENGTH_LONG).show();
				}
			}
		});

		courseListView.setAdapter(courseAdapter);

		fetchButton.setOnClickListener(new OnClickListener() {

			//@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (sceleService != null) {
					Toast.makeText(MainActivity.this, "Scele Service Not NULL",
							Toast.LENGTH_LONG).show();
					courses.addAll(sceleService.getCourses());
					for (Course c : courses) {
						Log.v("Course : ", c.getName() + c.getUrl());
					}
					courseAdapter.notifyDataSetChanged();
					// listView.

					fetchButton.setVisibility(View.GONE);
				} else {

					Toast.makeText(MainActivity.this, "Scele Service NULL",
							Toast.LENGTH_LONG).show();
				}
			}
		});
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		bindToService();

	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	private void bindToService() {
		Intent service = new Intent(this, SceleService.class);
		bindService(service, sceleServiceConnection, Context.BIND_AUTO_CREATE);

	}
	
		
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.afterlogin_menu, menu);
	    return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		//intent for settings
		Intent intent  = new Intent(MainActivity.this, SettingsActivity.class);
		//toast for others
		Context context = getApplicationContext();
		CharSequence help = "SceleDroid";
		int duration = Toast.LENGTH_LONG;
		Toast toast = Toast.makeText(context, help, duration);
		
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.help:
	       // showHelp();
	    	toast.show();
	        return true;
	    case R.id.settings:
	    	startActivity(intent);
	    	return true;
	    case R.id.credits:
	    	toast.show();
	    	//credits here;
	    	return true;
	    case R.id.logout:
	    	SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
			Editor e = pref.edit();//this.getPreferences(Context.MODE_PRIVATE).edit();
			e.clear();
			e.commit();
			intent = new Intent(MainActivity.this, LoginActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	    	startActivity(intent);
	    	return true;
	    case R.id.search:
	    	intent = new Intent(MainActivity.this, SearchActivity.class);
	    	startActivity(intent);
	    	return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}

}
